package com.ruoyi.system.controller;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.json.JSONObject;
import com.ruoyi.common.utils.CalcUtil;
import com.ruoyi.common.utils.CollectionUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.IAlpAuthorityService;
import com.ruoyi.system.service.IAlpCalcService;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.models.auth.In;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.service.IAlpMonthlyService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 月度汇总表Controller
 * 
 * @author zhangjun
 * @date 2020-02-21
 */
@Controller
@RequestMapping("/system/monthly")
public class AlpMonthlyController extends BaseController
{
    private String prefix = "system/monthly";

    @Autowired
    private IAlpMonthlyService alpMonthlyService;

    @Autowired
    private IAlpCalcService alpCalcService;

    @Autowired
    private IAlpAuthorityService authorityFilter;

    @RequiresPermissions("system:monthly:view")
    @GetMapping()
    public String monthly()
    {
        return prefix + "/monthlyList";
        //return prefix + "/monthly";
    }

    /**
     * 月汇总公司级
     */
    @RequiresPermissions("system:monthly:view")
    @PostMapping("/totalList")
    @ResponseBody
    public TableDataInfo totalList(){
        List<Map> list = alpMonthlyService.getTotalMonthlyList();
        return getDataTable(list);
    }

    /**
     * 月汇总部门级
     */
    @RequiresPermissions("system:monthly:view")
    @PostMapping("/deptList")
    @ResponseBody
    public TableDataInfo deptList(String deptName){
        String deptNames = authorityFilter.authorityDeptFilter(deptName);
        if (StringUtils.isEmpty(deptNames)) {
            List<Map> list = new ArrayList<>();
            return getDataTable(list);
        }
        List<Map> list = alpMonthlyService.getDeptMonthlyList(deptNames);
        return getDataTable(list);
    }


    /**
     * 月汇总个人级
     */
    @RequiresPermissions("system:monthly:view")
    @PostMapping("/personalList")
    @ResponseBody
    public TableDataInfo personalList(String personName){
        String personNames = authorityFilter.authorityPersonFilter(personName);
        if (StringUtils.isEmpty(personNames)) {
            List<Map> list = new ArrayList<>();
            return getDataTable(list);
        }
        List<Map> list = alpMonthlyService.getPersonalMonthlyList(personNames.toString());
        return getDataTable(list);
    }

    /**
     * 查询月度汇总表列表
     */
//    @RequiresPermissions("system:monthly:list")
//    @PostMapping("/list")
//    @ResponseBody
//    public TableDataInfo list(AlpMonthly alpMonthly)
//    {
//        startPage();
//        List<AlpMonthly> list = alpMonthlyService.selectAlpMonthlyList(alpMonthly);
//        return getDataTable(list);
//    }

    /**
     * 查询月度汇总表列表
     */
    @RequiresPermissions("system:monthly:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(AlpMonthly alpMonthly)
    {
        startPage();

        //key:销售名字   value：该销售 12个月 汇总
        HashMap<String,ArrayList<AlpElementCalc>> principalMap = new HashMap<>();
        HashMap<String,ArrayList<AlpElementCalc>> oneSalePrincipalMap = alpCalcService.getAllElementCalc();
        HashMap<Integer,ArrayList<AlpElementCalc>> oneMonthPrincipalMap = new HashMap<>();


//        //1销售     按月分组
//        ArrayList<AlpElementCalc> monthElementCalcList = new ArrayList<>();
//        for (Map.Entry<String, ArrayList<AlpElementCalc>> oneSaleEntry : oneSalePrincipalMap.entrySet()) {
//            ArrayList<AlpElementCalc> temp = oneSaleEntry.getValue();
//            BigDecimal resultActual = new BigDecimal(0);
//            BigDecimal resultBudget = new BigDecimal(0);
//            BigDecimal resultPredict = new BigDecimal(0);
//            for (int i = 1; i <=12; i++) {
//                for (AlpElementCalc element : temp) {
//                    if (i == element.getMonth()) {
//                        //各月份的计算逻辑
//                        resultBudget.add(element.getBudget());
//                        resultPredict.add(element.getPredict());
//                        resultActual.add(element.getActual());
//                    }
//                }
//                //每月 创建一个
//                AlpElementCalc monthAlp = new AlpElementCalc();
//                monthAlp.setMonth(i);
//                monthAlp.setActual(resultActual);
//                monthAlp.setBudget(resultBudget);
//                monthAlp.setPredict(resultPredict);
//
//                monthElementCalcList.add(monthAlp);
//            }
//
//            principalMap.put(oneSaleEntry.getKey(), monthElementCalcList);
//        }
//
//
//        System.out.println("########月度principalMap#########"+JSON.toJSONString(principalMap));


        //迭代到 各个月进行计算
        List<AlpMonthly> list = new ArrayList<>();
        Field[] fields = AlpMonthly.class.getFields();
        try {
            for (String key : oneSalePrincipalMap.keySet()) {
                AlpMonthly monthly = new AlpMonthly();
                monthly.setPrincipalName(key);
                ArrayList<AlpElementCalc> values = oneSalePrincipalMap.get(key);
                for (AlpElementCalc value : values) {
                    System.out.println("%%%%%%%%%%%"+JSON.toJSONString(value));
                    for (Field field : fields) {
                        //第三步：获取字段的名称
                        String fieldName = field.getName();
                        int fieldMonth = Integer.valueOf(fieldName.substring(1,3));
                        if (value.getMonth() == fieldMonth) {
                            if (fieldName.contains("Budget")) {
                                field.set(monthly, value.getBudget());
                            } else if (fieldName.contains("Actual")) {
                                field.set(monthly, value.getActual());
                            } else if (fieldName.contains("Predict")) {
                                field.set(monthly, value.getPredict());
                            } else if (fieldName.contains("FinishrateB")) {
                                field.set(monthly, CalcUtil.calcRate(value.getActual(), value.getBudget()));
                            } else if (fieldName.contains("FinishrateP")) {
                                field.set(monthly, CalcUtil.calcRate(value.getActual(), value.getPredict()));
                            } else if (fieldName.contains("Remainsum")) {
                                if (!CalcUtil.zero.equals(value.getBudget())) {
                                    field.set(monthly, value.getBudget().subtract(value.getActual()));
                                }
                            }
                        }
                    }
                }
                list.add(monthly);
            }
            System.out.println("%%%%%list%%%%%%"+JSON.toJSONString(list));

        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return getDataTable(list);
    }

    /**
     * 导出月度汇总表列表
     */
    @RequiresPermissions("system:monthly:export")
    @Log(title = "月度汇总表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(AlpMonthly alpMonthly)
    {
        List<AlpMonthly> list = alpMonthlyService.selectAlpMonthlyList(alpMonthly);
        ExcelUtil<AlpMonthly> util = new ExcelUtil<AlpMonthly>(AlpMonthly.class);
        return util.exportExcel(list, "monthly");
    }

    /**
     * 新增月度汇总表
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存月度汇总表
     */
    @RequiresPermissions("system:monthly:add")
    @Log(title = "月度汇总表", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(AlpMonthly alpMonthly)
    {
        return toAjax(alpMonthlyService.insertAlpMonthly(alpMonthly));
    }

    /**
     * 修改月度汇总表
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        AlpMonthly alpMonthly = alpMonthlyService.selectAlpMonthlyById(id);
        mmap.put("alpMonthly", alpMonthly);
        return prefix + "/edit";
    }

    /**
     * 修改保存月度汇总表
     */
    @RequiresPermissions("system:monthly:edit")
    @Log(title = "月度汇总表", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(AlpMonthly alpMonthly)
    {
        return toAjax(alpMonthlyService.updateAlpMonthly(alpMonthly));
    }

    /**
     * 删除月度汇总表
     */
    @RequiresPermissions("system:monthly:remove")
    @Log(title = "月度汇总表", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(alpMonthlyService.deleteAlpMonthlyByIds(ids));
    }
}
